const { AppError } = require('../middlewares/errorHandler');
const { logger } = require('../utils/logger');
const fileService = require('../services/file.service');

class FileController {
  /**
   * 上传文件
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async upload(ctx) {
    const { files } = ctx.request.files;
    const { bucket = 'default', path = '', access = 'private' } = ctx.request.body;

    if (!files || !Array.isArray(files)) {
      throw new AppError(400, 'No files uploaded');
    }

    try {
      const results = await Promise.all(
        files.map(file => fileService.upload(file, { bucket, path, access }))
      );

      ctx.status = 201;
      ctx.body = {
        status: 'success',
        data: { files: results }
      };
    } catch (error) {
      throw new AppError(500, error.message);
    }
  }

  /**
   * 下载文件
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async download(ctx) {
    const { fileId } = ctx.params;
    const { download = false } = ctx.query;

    try {
      const file = await fileService.download(fileId);
      
      if (download) {
        ctx.attachment(file.originalName);
      }

      ctx.body = file.stream;
      ctx.type = file.mimeType;
    } catch (error) {
      throw new AppError(404, 'File not found');
    }
  }

  /**
   * 删除文件
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async delete(ctx) {
    const { fileId } = ctx.params;

    try {
      await fileService.delete(fileId);
      ctx.body = {
        status: 'success',
        message: 'File deleted successfully'
      };
    } catch (error) {
      throw new AppError(404, 'File not found');
    }
  }

  /**
   * 获取文件信息
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async getInfo(ctx) {
    const { fileId } = ctx.params;

    try {
      const info = await fileService.getInfo(fileId);
      ctx.body = {
        status: 'success',
        data: { file: info }
      };
    } catch (error) {
      throw new AppError(404, 'File not found');
    }
  }

  /**
   * 获取文件列表
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async list(ctx) {
    const { bucket = 'default', path = '', page = 1, limit = 10 } = ctx.query;

    try {
      const files = await fileService.list({
        bucket,
        path,
        page: parseInt(page),
        limit: parseInt(limit)
      });

      ctx.body = {
        status: 'success',
        data: { files }
      };
    } catch (error) {
      throw new AppError(400, error.message);
    }
  }

  /**
   * 创建存储桶
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async createBucket(ctx) {
    const { name, access = 'private' } = ctx.request.body;

    try {
      const bucket = await fileService.createBucket(name, access);
      ctx.status = 201;
      ctx.body = {
        status: 'success',
        data: { bucket }
      };
    } catch (error) {
      throw new AppError(400, error.message);
    }
  }

  /**
   * 删除存储桶
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async deleteBucket(ctx) {
    const { name } = ctx.params;
    const { force = false } = ctx.query;

    try {
      await fileService.deleteBucket(name, force);
      ctx.body = {
        status: 'success',
        message: 'Bucket deleted successfully'
      };
    } catch (error) {
      throw new AppError(400, error.message);
    }
  }

  /**
   * 获取存储桶信息
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async getBucketInfo(ctx) {
    const { name } = ctx.params;

    try {
      const info = await fileService.getBucketInfo(name);
      ctx.body = {
        status: 'success',
        data: { bucket: info }
      };
    } catch (error) {
      throw new AppError(404, 'Bucket not found');
    }
  }

  /**
   * 更新存储桶访问权限
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async updateBucketAccess(ctx) {
    const { name } = ctx.params;
    const { access } = ctx.request.body;

    if (!['private', 'public-read', 'public-write'].includes(access)) {
      throw new AppError(400, 'Invalid access type');
    }

    try {
      const bucket = await fileService.updateBucketAccess(name, access);
      ctx.body = {
        status: 'success',
        data: { bucket }
      };
    } catch (error) {
      throw new AppError(404, 'Bucket not found');
    }
  }

  /**
   * 生成预签名URL
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async generatePresignedUrl(ctx) {
    const { fileId } = ctx.params;
    const { expiresIn = 3600 } = ctx.query; // Default 1 hour

    try {
      const url = await fileService.generatePresignedUrl(fileId, parseInt(expiresIn));
      ctx.body = {
        status: 'success',
        data: { url }
      };
    } catch (error) {
      throw new AppError(404, 'File not found');
    }
  }
}

module.exports = new FileController(); 